import {getToken, removeToken, setToken} from "@/utils/auth";
import {loginByPassword, loginByPhone, logout} from "@/api/user";

const state = {
    token: getToken(),
    userInfo:JSON.parse(localStorage.getItem("USER_INFO"))
};

const mutations = {
    SET_TOKEN:(state, token)=> {
        state.token = token;
    },
    SET_USERINFO:(state, userInfo)=> {
        state.userInfo = userInfo;
    },
    //清空本地缓存
    CLEAR:(state)=>{
        //帮仓库中先关用户信息清空
        state.token = '';
        state.userInfo={};
        //本地存储数据清空
        removeToken();
        localStorage.clear();
    }
}
const actions = {
    //密码登录
    LoginByPwd({commit},loginInfo){
        return new Promise((resolve,reject)=>{
            loginByPassword(loginInfo).then(res=>{
                console.log(res);
                setToken(res.content.token);
                commit('SET_TOKEN',res.content.token);
                commit('SET_USERINFO',res.content.userInfo)
                //将用户数据持久化到本地
                localStorage.setItem("USER_INFO",JSON.stringify(res.content.userInfo))
                resolve()
            }).catch(error =>{
                reject(error)
            })
        })
    },

    //手机号验证码登录
    LoginByPhoneCode({commit},loginInfo){
        return new Promise((resolve,reject)=>{
            loginByPhone(loginInfo).then(res=>{
                setToken(res.content.token);
                commit('SET_TOKEN',res.content.token);
                commit('SET_USERINFO',res.content.userInfo)
                //将用户数据持久化到本地
                localStorage.setItem("USER_INFO",JSON.stringify(res.content.userInfo))
                resolve()
            }).catch(error =>{
                reject(error)
            })
        })
    },

    //退出登录
    Logout({commit},userInfo){
        commit('CLEAR');
    }

}

const getters = {
};

export default {
    state,
    mutations,
    actions,
    getters,
};
